package com.lin.linchatgpt.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.lin.linchatgpt.entity.Message;
import com.lin.linchatgpt.entity.dto.MessageDTO;
import com.lin.linchatgpt.openai.server.ChatMessageService;
import com.lin.linchatgpt.service.MessageService;
import com.lin.linchatgpt.utils.LinResult;
import com.unfbx.chatgpt.entity.billing.Subscription;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;




/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/4/3 17:32
 * @Description
 */
@RestController
@CrossOrigin
@RequestMapping("lin_chat")
@SaCheckLogin
@Slf4j
public class ChatController {
    @Resource
    private ChatMessageService chatMessageService;
    @Resource
    private MessageService messageService;

    /**
     * @description 聊天
     * @author 霖霖
     * @date 2023/6/14 6:55
     * @params  [com.lin.linchatgpt.entity.Message, javax.servlet.http.HttpServletResponse]
     * @return  org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter
     */
    @PostMapping("chatMessage")
    public ResponseBodyEmitter chatMessage(@RequestBody MessageDTO messageDTO, HttpServletResponse response) {
        log.info("接收到的消息是：{}", messageDTO.getContent());
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
        return chatMessageService.sendMessage(messageDTO);
    }
    /**
     * @description 修改聊天信息
     * @author 霖霖
     * @date 2023/6/22 19:23
     * @params  [com.lin.linchatgpt.entity.Message, javax.servlet.http.HttpServletResponse]
     * @return  org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter
     */
    @PostMapping("modifyMessage")
    public ResponseBodyEmitter modifyMessage(@RequestBody Message message,HttpServletResponse response){
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
        List<Message> messages = messageService.modifyMessage(message);

        return chatMessageService.sendMessage(messages);
    }

    @GetMapping("apiKey")
    public LinResult apiKeyValid(HttpServletRequest request){
        String Authorization = request.getHeader("Authorization");
        String apikey = Authorization.split(" ")[1];
        log.info("apikey:{}",apikey);

        Subscription subscription = chatMessageService.validApiKey(apikey);
        Optional<Subscription> optional = Optional.ofNullable(subscription);

        if (optional.isPresent()){
            return LinResult.success().message("Key是正确的").data("subscription",subscription);
        }
        return LinResult.error().message("Key是错误的");
    }

    /**
     * @description 获取某个主题的聊天记录
     * @author 霖霖
     * @date 2023/6/14 21:36
     * @params  [java.lang.String]
     * @return  com.lin.linchatgpt.utils.LinResult
     */
    @GetMapping("messages/{subject}")
    public LinResult getMessages(@PathVariable("subject") String subjectId){
        return LinResult.success().data("messages",messageService.getMessages(subjectId));
    }



    @GetMapping("/data-stream")
    public ResponseBodyEmitter getDataStream(HttpServletResponse response) {
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
        // 创建一个 ResponseBodyEmitter 对象
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();

        // 启动一个异步线程，处理数据并逐步发送到客户端
        CompletableFuture.runAsync(() -> {
            try {
                // 处理数据并发送给客户端
                for (int i = 0; i < 10; i++) {
                    String data = "Data " + i;
                    System.out.println("发送数据：" + data);
                    emitter.send(data);
                    Thread.sleep(500);
                }
                // 发送完成信号
                emitter.complete();
            } catch (Exception e) {
                // 发送错误信息
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }

}
